package com.shenmazong.demosecurity0719.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2021/7/19 15:00
 */
@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    MyAuthenticationProvider myAuthenticationProvider;

    /**
     * @description 定义密码的加密算法（新版本要求密码必须加密）
     * @author 军哥
     * @date 2021/7/19 15:42
     * @version 1.0
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * @description 用户登录相关的配置函数
     * @author 军哥
     * @date 2021/7/19 15:03
     * @version 1.0
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(myAuthenticationProvider);
    }

    /**
     * @description 权限控制的配置函数
     * @author 军哥
     * @date 2021/7/19 15:03
     * @version 1.0
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 所有请求都可以访问
        http.authorizeRequests()

                //--1 放行页面
                .antMatchers("/login", "/index").permitAll()

                //--2 其他所有url请求都需要验证
                .anyRequest().authenticated()

                //--3 设定登录相关页面
                .and()
                .formLogin()
                // 这个接口不需要自己来实现
                .loginProcessingUrl("/process")
                // 下面两个接口需要自己来实现
                .successForwardUrl("/success")
                .failureForwardUrl("/failure")

                //--4 跨域請求关闭
                .and().csrf().disable()
                //--5 资源下载权限关闭
                .headers().frameOptions().disable();
    }
}
